//
//  SDChatViewController.swift
//  SIMChat
//
//  Created by sagesse on 10/4/15.
//  Copyright © 2015 Sagesse. All rights reserved.
//  by yangfei
//  desc 添加返回上一页，以及支持滑动返回
//

import UIKit
import Starscream
import SwiftyJSON

class SDChatViewController: SIMChatViewController, WebSocketDelegate{

    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        SingletonLoginSocket.sharedInstance.webSocket.delegate = self
        
        // 自定义返回按钮
        let backButton = UIBarButtonItem(title: "く圈子", style: UIBarButtonItemStyle.Plain, target: self, action: "goBack")
        self.navigationItem.leftBarButtonItem = backButton
        
        
        // 弥补因为返回按钮被替换导致的边缘滑入手势失效的问题
        let gesture = UIPanGestureRecognizer(target: self, action: "goBack")
        self.view.addGestureRecognizer(gesture)
        
        let foldName = self.conversation.sender.identifier+"&"+self.conversation.receiver.identifier
        
        let home = NSHomeDirectory() as NSString;
        let docPath = home.stringByAppendingPathComponent("Documents") as NSString;
        
        let afterPath = docPath as String + "/flowerpot/" + foldName
        print("afterPath:"+afterPath)
        
        // Do any additional setup after loading the view.
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func goBack() {

        self.navigationController?.popViewControllerAnimated(true)
        Common.mainTabBarController.tabBar.hidden = false
    }
    
    func websocketDidConnect(socket: WebSocket){
        print("初始化已经连接服务器")
        
    }
    
    func websocketDidDisconnect(socket: WebSocket, error: NSError?){
        print("连接服务器断开")
    }
    
    func websocketDidReceiveMessage(socket: WebSocket, text: String){
        print("初始化服务器返回数据:\(text)")
        
        let json = JSON(data: text.dataUsingEncoding(NSUTF8StringEncoding)!)
        var uid:String?
        
        print("初始化json:\(json)")
        
        if(json["msgCode"].stringValue == "666666"){
            
            let ui = NSUserDefaults.standardUserDefaults().objectForKey("userId")
            
            if(ui != nil){
                uid = ui as? String
            }

            if(json["result"]["message_type"].stringValue == "1" && json["result"]["message_to"].stringValue == uid){
                
                let text = json["result"]["message_content"].stringValue
                print(text)
                let foldName = self.conversation.sender.identifier+"&"+self.conversation.receiver.identifier+"/"
                
                let filePath = NSUUID().UUIDString + "$" + self.conversation.receiver.identifier+".txt"
                
                let isOk = Common.createFile(foldName,filePath: filePath, fileContent: text)
                if(isOk){
                    print("保存回复文本成功:"+filePath)
                }else{
                    print("保存回复文本失败!")
                }
                let sct = SIMChatMessage(SIMChatMessageContentText(text: text),type: 1)
                sct.receiveTime =  NSDate.now
                
                self.conversation.reciveMessageForRemote(sct)
                
            }
            
        }else{
            print("获取回复消息失败!")
        }
        
    }

    func websocketDidReceiveData(socket: WebSocket, data: NSData){

        
        let firstData = data.subdataWithRange(NSMakeRange(0, 1))
        if let flag = NSString(data: firstData, encoding: NSUTF8StringEncoding) as? String {
            print(flag)
            let datas = data.subdataWithRange(NSMakeRange(1, data.length-1))
            if(flag == "2"){
                
                let foldName = self.conversation.sender.identifier+"&"+self.conversation.receiver.identifier+"/"
                
                let im = UIImage.init(data: datas)
                
                let fd = Common.getFoldName(foldName)
                
                let filePath = fd + NSUUID().UUIDString + "$" + self.conversation.receiver.identifier + ".png"
                print("filePath:"+filePath)
                let isOk = datas.writeToFile(filePath, atomically: true)
                if(isOk){
                    print("创建图片成功:"+filePath)
                }else{
                    print("创建图片失败!")
                }
                
                //NSData.is
                let scm = SIMChatMessage(SIMChatMessageContentImage(origin: im, thumbnail: im),type: 2)
                scm.receiveTime =  NSDate.now
                self.conversation.reciveMessageForRemote(scm)
                
            }else if(flag == "3"){
                
                let foldName = self.conversation.sender.identifier+"&"+self.conversation.receiver.identifier+"/"
                let fd = Common.getFoldName(foldName)
                let filePath = fd + NSUUID().UUIDString + "$" + self.conversation.receiver.identifier + ".acc"
                print("filePathAudio:"+filePath)
                let isOk = datas.writeToFile(filePath, atomically: true)
                
                if(isOk){
                    
                    print("创建音频成功:"+filePath)
                    let url = NSURL.init(fileURLWithPath: filePath)
                    let sca = SIMChatMessage(SIMChatMessageContentAudio(url: url, duration: 2),type: 3)
                    sca.receiveTime =  NSDate.now
                    self.conversation.reciveMessageForRemote(sca)
                }else{
                    print("创建音频失败!")
                }
                
                
            }
            
        } else {
            print("解析二进制文件出错!")
        }
        
    }
    

}
